<template>
  <div v-loading="loading" class="follow-up-detail common-page">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="bg-white sticky top-0 z-10">
        <div class="flex items-center py-3">
          <el-button :icon="ArrowLeft" text class="!p-2 mr-2" @click="goBack" />
          <span class="text-lg font-medium">{{
            t("followUpPlan.detail.title")
          }}</span>
        </div>
      </div>
    </div>

    <!-- 基本信息展示 -->
    <div class="basic-info-display">
      <!-- 第一行 -->
      <div class="info-row">
        <div class="info-item">
          <span class="info-label"
            >{{ t("followUpPlan.detail.basicInfo.followUpPerson") }}:</span
          >
          <span class="info-value">{{ followData?.userName || "-" }}</span>
        </div>
        <div class="info-item">
          <span class="info-label"
            >{{ t("followUpPlan.detail.basicInfo.followUpDate") }}:</span
          >
          <span class="info-value">{{
            new Date(followData.startDate).toLocaleDateString()
          }}</span>
        </div>
        <div class="info-item">
          <span class="info-label"
            >{{ t("followUpPlan.detail.basicInfo.followUpTime") }}:</span
          >
          <span class="info-value">{{
            new Date(followData.startDate).toLocaleTimeString()
          }}</span>
        </div>
      </div>

      <!-- 备注 -->
      <div class="info-row full-width">
        <div class="info-item-full">
          <span class="info-label"
            >{{ t("followUpPlan.detail.basicInfo.notes") }}:</span
          >
          <div class="info-value remark-content">
            {{ followData.notes }}
          </div>
        </div>
      </div>
    </div>

    <!-- 标签页区域 -->
    <div class="tabs-section">
      <el-tabs v-model="activeTab" class="follow-up-tabs" type="border-card">
        <el-tab-pane
          :label="t('followUpPlan.detail.tabs.archive')"
          name="archive"
        >
          <ArchivesUpdateComponent
            v-if="activeTab === 'archive'"
            :userId="followData?.userId"
          />
        </el-tab-pane>

        <el-tab-pane
          :label="t('followUpPlan.detail.tabs.advice')"
          name="advice"
        >
          <AdviceComponent
            v-if="activeTab === 'advice'"
            :reportId="Number(route.query.userId)"
            :reportType="4"
            :isCreate="true"
            :requestSource="2"
          />
        </el-tab-pane>

        <el-tab-pane :label="t('followUpPlan.detail.tabs.risk')" name="risk">
          <RiskAssessmentComponent
            v-if="activeTab === 'risk'"
            :reportId="Number(route.query.userId)"
            :reportType="4"
            :isCreate="true"
            :requestSource="'2'"
          />
        </el-tab-pane>

        <el-tab-pane
          :label="t('followUpPlan.detail.tabs.examination')"
          name="examination"
        >
          <exam-plan
            ref="examPlanRef"
            :user-id="Number(followData?.userId || route.query.userId)"
            :plan-id="route.params.planId || route.query.planId"
            :mode="'create'"
          />
          <div class="drawer-footer">
            <el-button type="primary" @click="handleSubmit">保存</el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane
          :label="t('followUpPlan.detail.tabs.vaccine')"
          name="vaccine"
        >
          <vaccine-plan
            ref="vaccinePlanRef"
            :user-id="Number(followData?.userId || route.query.userId)"
            :plan-id="route.params.planId || route.query.planId"
            :mode="'create'"
          />
          <div class="drawer-footer">
            <el-button type="primary" @click="handleSubmitVaccine"
              >保存</el-button
            >
          </div>
        </el-tab-pane>

        <el-tab-pane :label="t('followUpPlan.detail.tabs.other')" name="other">
          <!-- 其他记录组件占位 -->
          <div class="tab-content-placeholder">
            <!-- OtherRecordsComponent 组件将在这里 -->
            <p class="placeholder-text">
              <el-input
                v-model="otherRecords"
                type="textarea"
                name=""
                class="w-full"
              />
            </p>
          </div>
          <div class="drawer-footer">
            <el-button type="primary" @click="handleSubmitOther"
              >保存</el-button
            >
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { followApi, FollowPlanDetailResponse } from "@/api/follow";
import { healthApi } from "@/api/health";
import ArchivesUpdateComponent from "@/views/followUpPlan/components/archivesUpdate.vue";
import AdviceComponent from "@/views/healthRecords/advice.vue";
import RiskAssessmentComponent from "@/views/healthRecords/riskAssessment.vue";
import { ArrowLeft } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import ExamPlan from "./components/examPlan.vue";
import VaccinePlan from "./components/vaccinePlan.vue";
// 扩展接口以包含可能缺失的属性
interface ExtendedFollowPlanDetail extends Partial<FollowPlanDetailResponse> {
  userName?: string;
  executionTime?: string;
}

const router = useRouter();
const route = useRoute();
const { t } = useI18n();
const examPlanRef = ref(null);
const vaccinePlanRef = ref(null);
const activeTab = ref("archive");
const loading = ref(false);
const followData = ref<ExtendedFollowPlanDetail>({});
const edit = ref<"view" | "edit" | "create">("view"); // 添加 edit 模式变量
// 返回上一页
const goBack = () => {
  router.back();
};
const otherRecords = ref("");
const getArchiveDetail = async () => {
  try {
    const response = await healthApi.getDetail({
      userId: Number(route.query.userId)
    });

    if (response.code === 0 && response.data) {
      // 设置其他记录数据 (临时处理类型问题)
      otherRecords.value = (response.data as any).otherRecords || "";
    } else {
      ElMessage.error(response.message || "获取其他记录数据失败");
    }
  } catch (error) {
    ElMessage.error("获取其他记录数据时发生异常，请稍后重试");
  }
};
// 获取随访计划详情
const getFollowPlanDetail = async () => {
  try {
    loading.value = true;

    // 从路由参数获取userId
    const taskId = route.params.taskId || route.query.taskId;

    const response = await followApi.getFollowUpPlanTaskDetail({
      taskId: String(taskId)
    });

    if (response.code === 0 && response.data) {
      followData.value = response.data;
    } else {
      ElMessage.error(
        response.message || t("followUpPlan.detail.errors.fetchDetailFailed")
      );
    }
  } catch (error) {
    console.error("获取随访计划详情失败:", error);
    ElMessage.error(t("followUpPlan.detail.errors.fetchDetailFailedRetry"));
  } finally {
    loading.value = false;
  }
};
const handleSubmit = () => {
  examPlanRef.value.submitForm();
};
const handleSubmitOther = () => {
  healthApi
    .getHealthArchiveUpdateOtherRecord({
      archiveId: Number(route.query.userId),
      otherRecords: otherRecords.value,
      requestSource: 4
    })
    .then(res => {
      if (res.code === 0) {
        ElMessage.success(t("followUpPlan.detail.messages.submitSuccess"));
      } else {
        ElMessage.error(res.message);
      }
    });
};
const handleSubmitVaccine = () => {
  vaccinePlanRef.value.submitForm();
};

// 监听 activeTab 变化，当切换到 "other" 标签时加载其他记录数据
watch(activeTab, newTab => {
  // 当切换到 "other" 标签时，调用接口获取数据
  if (newTab === "other") {
    console.log("进入其他记录标签，开始加载数据...");
    getArchiveDetail();
  }
});
// 页面加载时获取基本数据
onMounted(() => {
  getFollowPlanDetail();
});
</script>
<style scoped lang="scss">
.basic-info-display {
  padding: 24px;
}

.info-row {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
  align-items: flex-start;
}

.info-row.full-width {
  flex-direction: column;
}

.info-item {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

.info-item-full {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

.info-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
  width: 70px;
  text-align: right;
}

.info-value {
  font-size: 16px;
  color: #333;
  min-height: 20px;
}

.remark-content,
.info-value {
  font-weight: 400;
  font-size: 14px;
  color: #000000;
}

@media (max-width: 768px) {
  .info-row {
    flex-direction: column;
    gap: 16px;
  }
}
.drawer-footer {
  display: flex;
  justify-content: end;
  gap: 12px;
  padding: 16px 0;
}
</style>
